<template>
  <div class="process-route-add-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>{{ isEditMode ? '编辑工艺路线' : '新增工艺路线' }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="section-title">基础信息</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px" class="detail-form">
        <div class="two-col">
          <el-form-item label="工艺路线编号" prop="process_routecode">
            <div class="code-field">
              <el-input v-model="form.process_routecode" placeholder="请输入" :disabled="autoGenerateCode" />
              <el-switch v-model="autoGenerateCode" inline-prompt active-text="系统编号" inactive-text="手动输入" @change="handleCodeSwitchChange" />
            </div>
          </el-form-item>
          <el-form-item label="工艺路线名称" prop="process_routename" required>
            <el-input v-model="form.process_routename" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio-button :label="1">启用</el-radio-button>
              <el-radio-button :label="2">禁用</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="说明">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" :rows="4" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="section-title">工序组成</span>
          <el-badge :value="processNodeList.length" class="badge-icon" />
        </div>
      </template>
      <div class="toolbar">
        <el-button type="primary" @click="openProcessNodeDialog">新增</el-button>
        <el-button type="primary" plain :disabled="!processNodeSelection.length" @click="handleEditProcessNode">编辑</el-button>
        <el-button type="danger" plain :disabled="!processNodeSelection.length" @click="handleBatchDeleteProcessNode">删除</el-button>
      </div>
      <el-table :data="ProcesscompositionList" border stripe class="section-table" @selection-change="handleProcessNodeSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="process_nodecode" label="工序编号" min-width="140" />
        <el-table-column prop="processname" label="工序名称" min-width="160" />
        <el-table-column prop="nextprocessname" label="下一道工序" min-width="140" />
        <el-table-column prop="nextprocessrelation" label="与下一道工序关系" min-width="160" />
        <el-table-column prop="iskeyprocess" label="关键工序" width="100" align="center">
          <template #default="scope">
            <span>{{ scope.row.iskeyprocess ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="preparationtime" label="准备时间" width="100" align="center">
          <template #default="scope">
            <span>{{ formatTime(scope.row.preparationtime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="waitingtime" label="等待时间" width="100" align="center">
          <template #default="scope">
            <span>{{ formatTime(scope.row.waitingtime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="80" align="center">
          <template #default="scope">
            <div class="color-indicator" :style="{ backgroundColor: scope.row.color || '#409EFF' }"></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEditProcessNodeRow(scope.row)">编辑</el-button>
            <el-divider direction="vertical" />
            <el-button type="danger" link @click="handleDeleteProcessNode(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="section-title">关联物料</span>
        </div>
      </template>
      <div class="toolbar">
        <el-button type="primary" @click="openProductDialog">添加</el-button>
        <el-button type="danger" plain :disabled="!relatedMaterialSelection.length" @click="handleBatchRemoveMaterial">移除</el-button>
      </div>
      <el-table :data="relatedMaterialList" border stripe class="section-table" @selection-change="handleRelatedMaterialSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="materialcard" label="物料编号" min-width="140" />
        <el-table-column prop="materialname" label="物料名称" min-width="160" />
        <el-table-column prop="materialmodelsame" label="规格型号" min-width="120" />
        <el-table-column prop="materialunit" label="单位" width="80" align="center" />
        <el-table-column prop="usagequantity" label="使用量" width="100" align="center" />
        <el-table-column prop="proportion" label="比例" width="100" align="center" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button type="danger" link @click="handleRemoveMaterial(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

     <div class="action-bar">
       <el-button @click="handleCancel">取消</el-button>
       <el-button type="primary" @click="process_routeAdd">{{ isEditMode ? '保存' : '确定' }}</el-button>
     </div>

    <!-- 添加工序节点对话框 -->
    <el-dialog v-model="processNodeDialog.visible" :title="processNodeEditMode ? '编辑工序' : '添加工序'" width="800px" :close-on-click-modal="false">
      <el-form ref="processNodeFormRef" :model="processNodeForm" :rules="processNodeRules" label-width="120px" class="process-node-form">
        <div class="two-col">
          <el-form-item label="序号" prop="process_nodecode">
            <el-input v-model="processNodeForm.process_nodecode" placeholder="留空自动生成" />
          </el-form-item>
          <el-form-item label="工序" prop="processid" required>
            <el-select v-model="processNodeForm.processid" placeholder="请选择工序" clearable filterable class="w-full">
              <el-option
                v-for="item in processOptions"
                :key="item.id"
                :label="item.processname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="下一道工序">
            <el-select v-model="processNodeForm.nextprocessid" placeholder="请选择工序" clearable filterable class="w-full">
              <el-option
                v-for="item in processOptions"
                :key="item.id"
                :label="item.processname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关系">
            <el-select v-model="processNodeForm.nextprocessrelation" placeholder="请选择与下一道工序关系" clearable class="w-full">
              <el-option label="S-S" value="S-S" />
              <el-option label="S-F" value="S-F" />
              <el-option label="F-S" value="F-S" />
              <el-option label="F-F" value="F-F" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键工序">
            <el-radio-group v-model="processNodeForm.iskeyprocess">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="显示颜色">
            <div class="color-picker-field">
              <el-color-picker v-model="processNodeForm.color" />
              <el-input v-model="processNodeForm.color" placeholder="#1B9AEE" style="flex: 1; margin-left: 12px;" />
            </div>
          </el-form-item>
          <el-form-item label="准备时间">
            <div class="time-field">
              <el-input-number v-model="processNodeForm.preparationtime" :min="0" :precision="2" placeholder="请输入" />
              <span class="unit-text">小时</span>
            </div>
          </el-form-item>
          <el-form-item label="等待时间">
            <div class="time-field">
              <el-input-number v-model="processNodeForm.waitingtime" :min="0" :precision="2" placeholder="请输入" />
              <span class="unit-text">小时</span>
            </div>
          </el-form-item>
        </div>
        <el-form-item label="备注">
          <el-input v-model="processNodeForm.process_nodebz" type="textarea" :rows="4" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processNodeDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="processNodeSubmitLoading" @click="handleProcessNodeSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加物料对话框 -->
    <el-dialog v-model="materialDialog.visible" title="添加物料" width="1000px" :close-on-click-modal="false">
      <!-- 搜索和筛选区域 -->
      <div class="material-search-section">
        <el-form :inline="true" :model="materialSearchForm" class="material-search-form">
          <el-form-item label="">
            <el-input
              v-model="materialSearchForm.materialname"
              placeholder="请输入物料编号/名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="materialSearchForm.materialunit"
              placeholder="请选择单位"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="materialSearchForm.materialtypeid"
              placeholder="请选择类型"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in materialTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="materialSearchForm.materialclassificationid"
              placeholder="请选择物料分类"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in materialClassificationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleMaterialReset">重置</el-button>
            <el-button type="primary" @click="handleMaterialQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 物料列表表格 -->
      <el-table
        ref="materialTableRef"
        :data="materialDialog.tableData"
        border
        stripe
        v-loading="materialDialog.loading"
        @selection-change="handleMaterialSelectionChange"
        class="material-table"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="materialcard" label="物料编号" min-width="140" />
        <el-table-column prop="materialname" label="物料名称" min-width="160" />
        <el-table-column prop="materialmodelsame" label="规格型号" min-width="120" />
        <el-table-column prop="materialunit" label="单位" width="80" align="center" />
        <el-table-column prop="materialtypeid" label="物料类型" min-width="120">
          <template #default="scope">
            <span>{{ materialTypeMap.get(scope.row.materialtypeid) ?? '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="materialclassificationid" label="物料分类" min-width="120">
          <template #default="scope">
            <span>{{ materialClassificationMap.get(scope.row.materialclassificationid) ?? '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" />
      </el-table>

      <!-- 分页 -->
      <div class="material-pagination">
        <el-pagination
          v-model:current-page="materialDialog.pagination.page"
          v-model:page-size="materialDialog.pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="materialDialog.pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleMaterialSizeChange"
          @current-change="handleMaterialPageChange"
        />
      </div>

      <template #footer>
        <el-button @click="materialDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleMaterialConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
// 这是什么？本文件为“工艺路线新增页”的脚本部分，用于实现新增工艺路线页面的数据模型与基础交互逻辑。
// 包含表单数据、工序节点列表、关联产品列表，以及页面跳转处理。
import { ArrowRight, HomeFilled, Menu, Setting } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import https from '@/Http/http'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

const router = useRouter()
const route = useRoute()

// 判断是否为编辑模式
const isEditMode = computed(() => !!route.query.id)
const editId = computed(() => {
  const id = route.query.id
  return id ? Number(id) : null
})

// 工艺路线表单对象
const form = reactive({
  id: null as number | null,
  process_routecode: "",       // 工艺路线编号
  process_routename: '',       // 工艺路线名称
  status: 1,                   // 状态
  description: '',             // 说明
  remarks: ''                  // 备注
})
// 获取工艺路线详情
const fetchProcessRouteDetail = async () => {
  if (!editId.value) return

  try {
    // 从列表接口获取所有数据，然后在前端筛选
    const { data } = await https.Reads.get('/AManufacturing_process/AProcess_routeShow', {
      params: {
        pageindex: 1,
        pagesize: 1000  // 获取足够多的数据以便筛选
      }
    })

    const list = data?.data ?? data?.Data ?? []
    const item = list.find((x: any) => x.id === editId.value)
    
    if (item) {
      form.id = item.id
      form.process_routecode = item.process_routecode || ''
      form.process_routename = item.process_routename || ''
      form.status = item.status || 1
      form.description = item.description || ''
      form.remarks = item.remarks || ''

      // 加载关联数据
      if (form.process_routecode) {
        fetchProcesscompositionList()
        fetchRelatedMaterialsList()
      }
    } else {
      ElMessage.error('未找到工艺路线信息')
      router.push('/AProcess_routeView')
    }
  } catch (error) {
    console.error('获取工艺路线详情失败', error)
    ElMessage.error('获取工艺路线详情失败')
    router.push('/AProcess_routeView')
  }
}

// 保存工艺路线（新增或编辑）
const process_routeAdd = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 检查是否有工序节点（可选，根据业务需求）
    if (ProcesscompositionList.value.length === 0) {
      ElMessage.warning('请至少添加一个工序节点')
      return
    }

    try {
      if (isEditMode.value && editId.value) {
        // 编辑模式
        const editData = {
          id: editId.value,
          process_routecode: form.process_routecode?.trim(),
          process_routename: form.process_routename?.trim(),
          status: form.status,
          description: form.description?.trim() || null,
          remarks: form.remarks?.trim() || null
        }

        const response = await https.Writes.post("/AProcess_route/ProcessRouteEdit", editData)
        console.log('编辑工艺路线响应:', response)
        const data = extractPayload(response)
        
        if (isRequestSuccess(data)) {
          ElMessage.success(getResponseMessage(data, '编辑工艺路线成功'))
          router.push('/AProcess_routeView')
        } else {
          ElMessage.error(getResponseMessage(data, '编辑工艺路线失败'))
        }
      } else {
        // 新增模式
        // 确保必填字段不为空
        if (!form.process_routename?.trim()) {
          ElMessage.error('请输入工艺路线名称')
          return
        }
        
        const addData = {
          process_routecode: form.process_routecode?.trim() || null,
          process_routename: form.process_routename.trim(),
          status: form.status,
          description: form.description?.trim() || null,
          remarks: form.remarks?.trim() || null
        }
        
        console.log('新增工艺路线请求数据:', addData)
        const response = await https.Writes.post("/AProcess_route/ProcessRouteAdd", addData)
        console.log('新增工艺路线响应:', response)
        const data = extractPayload(response)
        
        if (isRequestSuccess(data)) {
          ElMessage.success(getResponseMessage(data, '新增工艺路线成功'))
          router.push('/AProcess_routeView')
        } else {
          ElMessage.error(getResponseMessage(data, '新增工艺路线失败'))
        }
      }
    } catch (error: any) {
      console.error('保存工艺路线失败', error)
      ElMessage.error(getErrorMessage(error, '保存工艺路线失败'))
    }
  })
}
// 工艺节点列表
const processNodeList = ref<any[]>([])

// 关联物料列表
const relatedMaterialList = ref<any[]>([])

// 物料选择对话框
const materialDialog = reactive({
  visible: false,
  loading: false,
  tableData: [] as any[],
  selectedMaterials: [] as any[],
  pagination: {
    page: 1,
    size: 10,
    total: 0
  }
})

// 物料搜索表单
const materialSearchForm = reactive({
  materialname: '',
  materialunit: undefined as string | undefined,
  materialtypeid: undefined as number | undefined,
  materialclassificationid: undefined as number | undefined
})

// 单位选项
const unitOptions = ref<Array<{ label: string; value: string }>>([
  { label: '个', value: '个' },
  { label: '件', value: '件' },
  { label: '箱', value: '箱' },
  { label: '包', value: '包' },
  { label: 'kg', value: 'kg' },
  { label: 'g', value: 'g' },
  { label: 'm', value: 'm' },
  { label: 'cm', value: 'cm' }
])

// 物料类型选项（示例数据，实际应从接口获取）
const materialTypeOptions = ref<Array<{ label: string; value: number }>>([
  { label: '类型一', value: 1 },
  { label: '类型二', value: 2 },
  { label: '类型三', value: 3 }
])

// 物料分类选项（示例数据，实际应从接口获取）
const materialClassificationOptions = ref<Array<{ label: string; value: number }>>([
  { label: '分类一', value: 1 },
  { label: '分类二', value: 2 },
  { label: '分类三', value: 3 }
])

const materialTypeMap = computed(() => {
  const map = new Map<number, string>()
  materialTypeOptions.value.forEach((item) => {
    map.set(item.value, item.label)
  })
  return map
})

const materialClassificationMap = computed(() => {
  const map = new Map<number, string>()
  materialClassificationOptions.value.forEach((item) => {
    map.set(item.value, item.label)
  })
  return map
})

// 物料表格引用
const materialTableRef = ref()

// 工序选项列表（动态下拉，待接入接口）
interface ProcessOption {
  id: number
  processname: string
  processcode: string
}
const processOptions = ref<ProcessOption[]>([])

// 工序节点对话框
const processNodeDialog = reactive({ visible: false })
const processNodeFormRef = ref<FormInstance>()
const processNodeSubmitLoading = ref(false)

// 工序节点表单
const processNodeForm = reactive({
  process_routecode: '', // 工艺路线编号，提交时从form中获取
  process_nodecode: '', // 序号（必填）
  processid: undefined as number | undefined, // 工序id（必填）
  nextprocessid: undefined as number | undefined, // 下一道工序ID
  nextprocessrelation: '', // 关系
  iskeyprocess: false, // 关键工序
  preparationtime: 0, // 准备时间（小时）
  waitingtime: 0, // 等待时间（小时）
  color: '#1B9AEE', // 颜色
  process_nodebz: '', // 备注
})

// 工序节点表单验证规则
const processNodeRules = reactive<FormRules>({
  processid: [{ required: true, message: '请选择工序', trigger: 'change' }],
})

// 工艺路线表单验证规则
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules>({
  process_routename: [{ required: true, message: '请输入工艺路线名称', trigger: 'blur' }],
  process_routecode: [{ required: true, message: '请输入工艺路线编号', trigger: 'blur' }]
})

// 系统编号自动生成开关
const autoGenerateCode = ref(false)

// 生成系统编号
const generateSystemCode = () => {
  return `GYLX${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
}

// 编号开关变化处理
const handleCodeSwitchChange = (val: boolean) => {
  if (val) {
    form.process_routecode = generateSystemCode()
  }
}

// 工序节点选择
const processNodeSelection = ref<any[]>([])
const handleProcessNodeSelectionChange = (selection: any[]) => {
  processNodeSelection.value = selection
}

// 关联物料选择
const relatedMaterialSelection = ref<any[]>([])
const handleRelatedMaterialSelectionChange = (selection: any[]) => {
  relatedMaterialSelection.value = selection
}

// 格式化时间（分钟转小时）
const formatTime = (minutes: number) => {
  if (!minutes) return '0小时'
  const hours = (minutes / 60).toFixed(2)
  return `${hours}小时`
}

// 工序节点编辑模式
const processNodeEditMode = ref(false)
const processNodeEditId = ref<number | null>(null)

// 打开添加工序节点对话框
const openProcessNodeDialog = () => {
  if (!form.process_routecode) {
    ElMessage.warning('请先填写工艺路线编号')
    return
  }
  // 重置表单
  processNodeEditMode.value = false
  processNodeEditId.value = null
  processNodeForm.process_routecode = form.process_routecode || ''
  processNodeForm.process_nodecode = ''
  processNodeForm.processid = undefined
  processNodeForm.nextprocessid = undefined
  processNodeForm.nextprocessrelation = ''
  processNodeForm.iskeyprocess = false
  processNodeForm.preparationtime = 0
  processNodeForm.waitingtime = 0
  processNodeForm.color = '#1B9AEE'
  processNodeForm.process_nodebz = ''
  processNodeFormRef.value?.clearValidate()
  processNodeDialog.visible = true
}

// 提交工序节点
const handleProcessNodeSubmit = async () => {
  if (!processNodeFormRef.value) return
  
  await processNodeFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    processNodeSubmitLoading.value = true
    try {
      // 自动生成序号（如果为空）
      if (!processNodeForm.process_nodecode?.trim()) {
        const maxCode = ProcesscompositionList.value.length > 0
          ? Math.max(...ProcesscompositionList.value.map((item: any) => {
              const code = item.process_nodecode || '0'
              const num = parseInt(code) || 0
              return num
            }))
          : 0
        processNodeForm.process_nodecode = String(maxCode + 1)
      }
      
      // 将小时转换为分钟（后端需要分钟），并设置工艺路线编号
      // 处理下一节点为空的情况，将 undefined 转换为 null
      const submitData = {
        ...processNodeForm,
        process_routecode: form.process_routecode || processNodeForm.process_routecode,
        process_nodecode: processNodeForm.process_nodecode.trim(),
        nextprocessid: processNodeForm.nextprocessid ?? null,
        preparationtime: Math.round(processNodeForm.preparationtime * 60),
        waitingtime: Math.round(processNodeForm.waitingtime * 60),
      }
      
      const response = await https.Writes.post('/AProcess_route/Aprocess_NodeAdd', submitData)
      const data = extractPayload(response)
      
      if (isRequestSuccess(data)) {
        ElMessage.success(getResponseMessage(data, '添加工序节点成功'))
        processNodeDialog.visible = false
        // 刷新工序组成列表
        await fetchProcesscompositionList()
      } else {
        ElMessage.error(getResponseMessage(data, '添加工序节点失败'))
      }
    } catch (error) {
      console.error('添加工序节点失败', error)
      ElMessage.error(getErrorMessage(error, '添加工序节点失败'))
    } finally {
      processNodeSubmitLoading.value = false
    }
  })
}

// 获取工序列表
const fetchProcessList = async () => {
  try {
    const { data } = await https.Reads.get('/AManufacturing_process/GetProcessList')
    const list = data?.data ?? []
    processOptions.value = list.map((item: any) => ({
      id: item.id,
      processname: item.processname,
      processcode: item.processcode,
    }))
  } catch (error) {
    console.error('获取工序列表失败', error)
    ElMessage.error('获取工序列表失败')
  }
}

const ProcesscompositionList = ref([])
// 获取工序组成列表
const fetchProcesscompositionList = async () => {
  try {
    const { data } = await https.Reads.get("/AManufacturing_process/GetProcessComposition", {
      params: {
        process_routecode: form.process_routecode
      }
    })
    ProcesscompositionList.value = data?.data ?? []
  } catch (error) {
    console.error('获取工序组成列表失败', error)
    ElMessage.error('获取工序组成列表失败')
  }
}

// 获取关联物料列表
const fetchRelatedMaterialsList = async () => {
  if (!form.process_routecode) {
    relatedMaterialList.value = []
    return
  }
  try {
    const { data } = await https.Reads.get("/AManufacturing_process/GetProcessMaterials", {
      params: {
        process_routecode: form.process_routecode
      }
    })
    relatedMaterialList.value = data?.data ?? []
  } catch (error) {
    console.error('获取关联物料列表失败', error)
    ElMessage.error('获取关联物料列表失败')
  }
}

// 取消按钮处理函数：返回工艺路线列表页
const handleCancel = () => {
  router.push('/AProcess_routeView')
}

// 打开物料选择对话框
const openProductDialog = () => {
  if (!form.process_routecode) {
    ElMessage.warning('请先填写工艺路线编号')
    return
  }
  materialDialog.visible = true
  materialDialog.selectedMaterials = []
  materialDialog.pagination.page = 1
  fetchMaterialList()
}

// 获取物料列表
const fetchMaterialList = async () => {
  materialDialog.loading = true
  try {
    const response = await https.Reads.get('/Material/MaterialGetList', {
      params: {
        materialname: materialSearchForm.materialname || undefined,
        materialtypeid: materialSearchForm.materialtypeid || undefined,
        materialclassificationid: materialSearchForm.materialclassificationid || undefined,
        pageindex: 1,
        pagesize: 10000  // 获取所有数据，前端进行过滤和分页
      }
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取物料列表失败'))
    }
    let allData = payload?.data ?? payload?.Data ?? []
    
    // 前端过滤单位（如果接口不支持单位查询）
    if (materialSearchForm.materialunit) {
      allData = allData.filter((item: any) => item.materialunit === materialSearchForm.materialunit)
    }
    
    // 前端分页处理
    const start = (materialDialog.pagination.page - 1) * materialDialog.pagination.size
    const end = start + materialDialog.pagination.size
    materialDialog.tableData = allData.slice(start, end)
    materialDialog.pagination.total = allData.length
  } catch (error) {
    console.error('获取物料列表失败', error)
    ElMessage.error(getErrorMessage(error, '获取物料列表失败'))
  } finally {
    materialDialog.loading = false
  }
}

// 物料表格多选变化
const handleMaterialSelectionChange = (selection: any[]) => {
  materialDialog.selectedMaterials = selection
}

// 物料查询
const handleMaterialQuery = () => {
  materialDialog.pagination.page = 1
  fetchMaterialList()
}

// 物料重置
const handleMaterialReset = () => {
  materialSearchForm.materialname = ''
  materialSearchForm.materialunit = undefined
  materialSearchForm.materialtypeid = undefined
  materialSearchForm.materialclassificationid = undefined
  handleMaterialQuery()
}

// 物料分页大小变化
const handleMaterialSizeChange = (size: number) => {
  materialDialog.pagination.size = size
  materialDialog.pagination.page = 1
  fetchMaterialList()
}

// 物料分页变化
const handleMaterialPageChange = (page: number) => {
  materialDialog.pagination.page = page
  fetchMaterialList()
}

// 确认选择物料（批量添加）
const handleMaterialConfirm = async () => {
  if (materialDialog.selectedMaterials.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }

  if (!form.process_routecode) {
    ElMessage.warning('请先填写工艺路线编号')
    return
  }

  try {
    // 调用批量添加工艺物料接口
    const materialIds = materialDialog.selectedMaterials.map((item: any) => item.id)
    const response = await https.Writes.post('/AProcess_route/ProcessMaterialsBatchAdd', {
      process_routecode: form.process_routecode.trim(),
      materialIds: materialIds
    })
    console.log('批量添加工艺物料响应:', response)

    const bindData = extractPayload(response)
    if (isRequestSuccess(bindData)) {
      ElMessage.success(getResponseMessage(bindData, '批量添加工艺物料成功'))
      
      // 清空选中状态
      materialDialog.selectedMaterials = []
      materialDialog.pagination.page = 1
      
      // 刷新关联物料列表
      await fetchRelatedMaterialsList()
      
      // 刷新完成后再关闭对话框
      materialDialog.visible = false
    } else {
      ElMessage.error(getResponseMessage(bindData, '批量添加工艺物料失败'))
    }
  } catch (error: any) {
    console.error('批量添加工艺物料失败', error)
    ElMessage.error(getErrorMessage(error, '批量添加工艺物料失败'))
  }
}

// 编辑工序节点（行操作）
const handleEditProcessNodeRow = (row: any) => {
  if (!form.process_routecode) {
    ElMessage.warning('请先填写工艺路线编号')
    return
  }
  processNodeEditMode.value = true
  processNodeEditId.value = row.id
  processNodeForm.process_routecode = form.process_routecode || ''
  processNodeForm.process_nodecode = row.process_nodecode || ''
  processNodeForm.processid = row.processid
  processNodeForm.nextprocessid = row.nextprocessid
  processNodeForm.nextprocessrelation = row.nextprocessrelation || ''
  processNodeForm.iskeyprocess = row.iskeyprocess || false
  processNodeForm.preparationtime = row.preparationtime ? row.preparationtime / 60 : 0
  processNodeForm.waitingtime = row.waitingtime ? row.waitingtime / 60 : 0
  processNodeForm.color = row.color || '#1B9AEE'
  processNodeForm.process_nodebz = row.process_nodebz || ''
  processNodeFormRef.value?.clearValidate()
  processNodeDialog.visible = true
}

// 编辑工序节点（批量选择）
const handleEditProcessNode = () => {
  if (processNodeSelection.value.length === 0) {
    ElMessage.warning('请选择要编辑的工序节点')
    return
  }
  if (processNodeSelection.value.length > 1) {
    ElMessage.warning('请只选择一个工序节点进行编辑')
    return
  }
  handleEditProcessNodeRow(processNodeSelection.value[0])
}

// 删除工序节点（行操作）
const handleDeleteProcessNode = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工序节点"${row.processname || row.process_nodecode}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // TODO: 调用后端删除接口（如果存在）
    // 目前先从前端列表移除
    const index = ProcesscompositionList.value.findIndex((item: any) => item.id === row.id)
    if (index > -1) {
      ProcesscompositionList.value.splice(index, 1)
      ElMessage.success('删除工序节点成功')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除工序节点失败', error)
      ElMessage.error('删除工序节点失败')
    }
  }
}

// 批量删除工序节点
const handleBatchDeleteProcessNode = async () => {
  if (processNodeSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的工序节点')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${processNodeSelection.value.length} 个工序节点吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // TODO: 调用后端批量删除接口（如果存在）
    // 目前先从前端列表移除
    const ids = processNodeSelection.value.map((item: any) => item.id)
    ProcesscompositionList.value = ProcesscompositionList.value.filter((item: any) => !ids.includes(item.id))
    processNodeSelection.value = []
    ElMessage.success('批量删除工序节点成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除工序节点失败', error)
      ElMessage.error('批量删除工序节点失败')
    }
  }
}

// 移除关联物料（行操作）
const handleRemoveMaterial = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除物料"${row.materialname || row.materialcard}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // TODO: 调用后端删除接口（如果存在）
    // 目前先从前端列表移除
    const index = relatedMaterialList.value.findIndex((item: any) => item.id === row.id)
    if (index > -1) {
      relatedMaterialList.value.splice(index, 1)
      ElMessage.success('移除物料成功')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除物料失败', error)
      ElMessage.error('移除物料失败')
    }
  }
}

// 批量移除关联物料
const handleBatchRemoveMaterial = async () => {
  if (relatedMaterialSelection.value.length === 0) {
    ElMessage.warning('请选择要移除的物料')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要移除选中的 ${relatedMaterialSelection.value.length} 个物料吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // TODO: 调用后端批量删除接口（如果存在）
    // 目前先从前端列表移除
    const ids = relatedMaterialSelection.value.map((item: any) => item.id)
    relatedMaterialList.value = relatedMaterialList.value.filter((item: any) => !ids.includes(item.id))
    relatedMaterialSelection.value = []
    ElMessage.success('批量移除物料成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量移除物料失败', error)
      ElMessage.error('批量移除物料失败')
    }
  }
}

// 监听工艺路线编号变化，自动刷新关联物料列表
watch(() => form.process_routecode, (newVal) => {
  if (newVal) {
    fetchRelatedMaterialsList()
    fetchProcesscompositionList()
  }
})

// 页面加载时获取工序列表和关联产品列表
onMounted(() => {
  fetchProcessList()
  
  // 如果是编辑模式，加载详情数据
  if (isEditMode.value && editId.value) {
    fetchProcessRouteDetail()
  } else if (form.process_routecode) {
    // 新增模式，如果有工艺路线编号，加载关联数据
    fetchProcesscompositionList()
    fetchRelatedMaterialsList()
  }
})
</script>

<style scoped>
.process-route-add-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.process-route-add-page::before {
  content: "";
  position: fixed;
  inset: 0;
  pointer-events: none;
  z-index: 0;
}

.process-route-add-page > * {
  position: relative;
  z-index: 1;
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  position: relative;
  overflow: hidden;
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.form-card {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.badge-icon {
  margin-left: 8px;
}

.detail-form {
  margin-top: 4px;
}

.two-col {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 24px;
}

.code-field {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.section-table {
  width: 100%;
}

.color-indicator {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  margin: 0 auto;
  border: 1px solid #dcdfe6;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
}

.process-node-form {
  margin-top: 4px;
}

.color-picker-field {
  display: flex;
  align-items: center;
  width: 100%;
}

.time-field {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.unit-text {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.w-full {
  width: 100%;
}

/* 物料选择对话框样式 */
.material-search-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.material-search-form {
  margin: 0;
}

.material-table {
  margin-bottom: 16px;
}

.material-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>


